package com.example.usercenter.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.usercenter.config.AlipayConfig;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/alipay")
public class AlipayController {
    private static final String GATE_WAY_HOST = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"; // 网关地址
    private static final String SIGN_TYPE = "RSA2"; // 验签方式
    private static final String CHARSET = "UTF-8";
    private static final String FORMAT = "JSON";

    @Resource
    private AlipayConfig alipayConfig;

    @GetMapping("/pay")
    public void pay(HttpServletResponse response) throws IOException {
        // 1. 创建通用SDK提供的client，负责调用支付宝API
        AlipayClient alipayClient = new DefaultAlipayClient(GATE_WAY_HOST, alipayConfig.getAppId(), alipayConfig.getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SIGN_TYPE);
        // 2. 创建Request与相应参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的request类
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();

        bizContent.put("out_trade_no", RandomUtil.randomString(16));
        bizContent.put("total_amount", 1);
        bizContent.put("subject", "打赏作者");
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toJSONString());
        request.setReturnUrl("http://49.235.188.164/");
        // 执行请求拿到响应结果
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws AlipayApiException {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> paramsMap = request.getParameterMap();
            for (String name : paramsMap.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), CHARSET);
            if (checkSignature) {
                // 验签通过
                System.out.println("交易名称：" + params.get("subject"));
                System.out.println("交易状态：" + params.get("trade_status"));
                System.out.println("支付宝交易凭证号：" + params.get("trade_no"));
                System.out.println("客户订单号：" + params.get("out_trade_no"));
                System.out.println("交易金额：" + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id：" + params.get("buyer_id"));
                System.out.println("买家付款时间：" + params.get("gmt_payment"));
                System.out.println("买家付款金额：" + params.get("buyer_pay_amount"));
            }
        }
    }
}
